package cn.mjnxin.iot.gate.worker;

import cn.mjnxin.iot.base.domain.ChannelData;
import cn.mjnxin.iot.base.log.LogWorker;
import cn.mjnxin.iot.base.process.DataProcessWorker;
import cn.mjnxin.iot.gate.cache.GateRuntimeCache;
import cn.mjnxin.iot.gate.util.GateUtil;
import io.netty.channel.Channel;

/**
 * 下行报文中转 
 * @Description: 前置报文经过网关中转实际发送终端
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class Gate2TerminalWorker extends DataProcessWorker<ChannelData> {
    private static Gate2TerminalWorker worker = null;
	//非单例模式：调用一次就初始化一次
    public  static void init(int poolSize) throws Exception {
    	worker = new Gate2TerminalWorker(poolSize);
    }
    
    public static Gate2TerminalWorker getInstance() {
    	return worker;
    }
    
    private Gate2TerminalWorker(int poolSize) throws Exception {
        super(poolSize, "Gate2TerminalWorker");
		this.start();
    }

	@Override
	protected void proccess(ChannelData channelData) throws Exception {
		String terminalAddress = channelData.getTerminalAddress();
		Channel channel = GateRuntimeCache.getTerminal(terminalAddress);
		Integer pid = channelData.getPid();
		int logLevel = channelData.getLogLevel();
		if(channel != null){
		    if (channel.isActive() && channel.isWritable()) {
		        channel.writeAndFlush(channelData);
		    }
		    else {
	            LogWorker.logForce(String.format("NS G->T[%s]=", terminalAddress), channelData.getSocketData().getByteBuf());
		        LogWorker.logForce(String.format("%d|%s Terminal不可写，主动断连", pid, terminalAddress));
		        //通知host，硬件断连
		        GateUtil.terminalUnlink(pid, logLevel, terminalAddress, GateRuntimeCache.gateNo);
		    }
		}
		else{
	        LogWorker.logForce(String.format("NS G->T[%s]=", terminalAddress), channelData.getSocketData().getByteBuf());
		    LogWorker.logForce(String.format("%d:%s Terminal为空，主动断连", pid, terminalAddress));
		    //通知host，硬件断连
		    GateUtil.terminalUnlink(pid, logLevel, terminalAddress, GateRuntimeCache.gateNo);
		}
	}
}
